<template>
  <div class="create-topic-page">
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">{{ isEdit ? '编辑话题' : '发表新话题' }}</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/forum' }">论坛首页</el-breadcrumb-item>
          <el-breadcrumb-item v-if="selectedBoard">{{ selectedBoard.name }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ isEdit ? '编辑话题' : '发表新话题' }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="main-content">
        <div class="form-container" v-loading="loading">
          <el-form 
            ref="topicFormRef" 
            :model="topicForm" 
            :rules="rules" 
            label-position="top"
          >
            <!-- 板块选择 -->
            <el-form-item label="选择板块" prop="boardId">
              <div class="board-selection">
                <el-select
                  v-model="topicForm.boardId"
                  placeholder="请选择板块"
                  style="width: 100%"
                  :disabled="boardFixed"
                  popper-class="board-select-dropdown"
                >
                  <el-option
                    v-for="board in boards"
                    :key="board.id"
                    :label="board.name"
                    :value="board.id"
                  >
                    <div class="board-option">
                      <div class="board-icon" :style="{ backgroundColor: board.color }">
                        <el-icon><component :is="board.icon" /></el-icon>
                      </div>
                      <div class="board-info">
                        <div class="board-name">{{ board.name }}</div>
                        <div class="board-desc">{{ board.description }}</div>
                      </div>
                    </div>
                  </el-option>
                </el-select>
              </div>
            </el-form-item>

            <!-- 话题标题 -->
            <el-form-item label="话题标题" prop="title">
              <el-input
                v-model="topicForm.title"
                placeholder="请输入话题标题（5-50个字符）"
                maxlength="50"
                show-word-limit
                class="title-input"
              />
            </el-form-item>

            <!-- 话题内容 -->
            <el-form-item label="话题内容" prop="content">
              <div class="editor-container">
                <!-- 基础的富文本编辑器 -->
                <el-input
                  v-model="topicForm.content"
                  type="textarea"
                  placeholder="请输入话题内容（50-10000个字符）"
                  :rows="15"
                  maxlength="10000"
                  show-word-limit
                  class="content-editor"
                />
              </div>
              
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
              <div class="form-actions">
                <el-button @click="goBack" class="cancel-btn">取消</el-button>
                <el-button 
                  type="primary" 
                  :loading="submitting"
                  @click="submitTopic"
                  class="submit-btn"
                >
                  <el-icon class="submit-icon"><DocumentAdd /></el-icon>
                  {{ isEdit ? '保存修改' : '发表话题' }}
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 发帖指南 -->
        <div class="posting-guide">
          <div class="guide-header">
            <h3 class="guide-title"><el-icon><Guide /></el-icon> 发帖指南</h3>
            <el-divider />
          </div>
          <div class="guide-content">
            <div class="guide-item">
              <div class="guide-icon"><el-icon><List /></el-icon></div>
              <div class="guide-text">请确保您的话题与所选板块相关，发布在合适的板块有助于获得更多回复。</div>
            </div>
            <div class="guide-item">
              <div class="guide-icon"><el-icon><Edit /></el-icon></div>
              <div class="guide-text">标题应简明扼要，能清晰表达您要讨论的主题。</div>
            </div>
            <div class="guide-item">
              <div class="guide-icon"><el-icon><Document /></el-icon></div>
              <div class="guide-text">内容应详实，提供足够的信息让他人理解您的问题或观点。</div>
            </div>
            <div class="guide-item">
              <div class="guide-icon"><el-icon><UserFilled /></el-icon></div>
              <div class="guide-text">请尊重他人，不要发布含有攻击性、侮辱性的言论。</div>
            </div>
            <div class="guide-item">
              <div class="guide-icon"><el-icon><Warning /></el-icon></div>
              <div class="guide-text">请不要发布广告或垃圾内容，这些内容可能会被管理员删除。</div>
            </div>
            <div class="guide-item">
              <div class="guide-icon"><el-icon><Picture /></el-icon></div>
              <div class="guide-text">如需上传图片，请确保图片内容合适，且大小不超过2MB。</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Briefcase, 
  Coin, 
  School, 
  Reading, 
  OfficeBuilding, 
  Guide,
  InfoFilled,
  DocumentAdd,
  Edit,
  Document,
  UserFilled,
  Warning,
  Picture,
  List
} from '@element-plus/icons-vue'
import { getForumBoards, createTopic, getTopicDetail, updateTopic } from '@/api/forum'

const route = useRoute()
const router = useRouter()
const topicFormRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 板块列表
const boards = ref([])

// 获取URL中的boardId参数
const urlBoardId = computed(() => {
  return route.query.boardId ? parseInt(route.query.boardId) : null
})

// 获取URL中的topicId参数（编辑模式）
const topicId = computed(() => {
  return route.params.id ? parseInt(route.params.id) : null
})

// 是否是编辑模式
const isEdit = computed(() => {
  return !!topicId.value
})

// 是否固定板块选择
const boardFixed = computed(() => {
  return !!urlBoardId.value || isEdit.value
})

// 当前选中的板块
const selectedBoard = computed(() => {
  return boards.value.find(b => b.id === topicForm.boardId)
})

// 表单数据
const topicForm = reactive({
  boardId: urlBoardId.value || '',
  title: '',
  content: ''
})

// 表单验证规则
const rules = {
  boardId: [
    { required: true, message: '请选择板块', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入话题标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度应在5到50个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入话题内容', trigger: 'blur' },
    { min: 50, max: 10000, message: '内容长度应在50到10000个字符之间', trigger: 'blur' }
  ]
}

// 获取板块列表
const fetchBoards = async () => {
  loading.value = true
  try {
    const res = await getForumBoards()
    if (res.code === 200) {
      boards.value = res.data.map(board => {
        // 映射图标名称到组件
        const iconMapping = {
          'briefcase': 'Briefcase',
          'coin': 'Coin',
          'school': 'School',
          'reading': 'Reading',
          'office-building': 'OfficeBuilding',
          'guide': 'Guide'
        }
        
        return {
          ...board,
          icon: iconMapping[board.icon] || 'Briefcase'
        }
      })
    }
  } catch (error) {
    console.error('获取板块列表失败', error)
    ElMessage.error('获取板块列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取话题详情（编辑模式）
const fetchTopicDetail = async () => {
  if (!isEdit.value) return
  
  loading.value = true
  try {
    const res = await getTopicDetail(topicId.value)
    if (res.code === 200) {
      // 填充表单数据
      topicForm.boardId = res.data.boardId
      topicForm.title = res.data.title
      topicForm.content = res.data.content
    }
  } catch (error) {
    console.error('获取话题详情失败', error)
    ElMessage.error('获取话题详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 提交话题
const submitTopic = async () => {
  // 表单验证
  await topicFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善所有必填项')
      return
    }
    
    submitting.value = true
    try {
      const data = {
        ...topicForm
      }
      
      let res
      
      if (isEdit.value) {
        // 编辑模式下使用updateTopic
        res = await updateTopic(topicId.value, data)
      } else {
        // 创建模式下使用createTopic
        res = await createTopic(data)
      }
      
      if (res.code === 200) {
        ElMessage.success(isEdit.value ? '话题更新成功' : '话题发表成功')
        
        // 跳转到话题详情页
        if (res.data && res.data.id) {
          router.push(`/forum/topics/${res.data.id}`)
        } else {
          // 如果没有返回id，则跳转到板块页
          router.push(`/forum/boards/${topicForm.boardId}`)
        }
      }
    } catch (error) {
      console.error(isEdit.value ? '更新话题失败' : '发表话题失败', error)
      ElMessage.error(isEdit.value ? '更新话题失败，请稍后重试' : '发表话题失败，请稍后重试')
    } finally {
      submitting.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  if (topicForm.title || topicForm.content) {
    ElMessageBox.confirm(
      '您的内容尚未保存，确定要离开吗？',
      '确认离开',
      {
        confirmButtonText: '确定离开',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    )
    .then(() => {
      router.back()
    })
    .catch(() => {
      // 用户取消离开
    })
  } else {
    router.back()
  }
}

// 检查用户登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录后再发表话题')
    router.push({
      path: '/auth/login',
      query: { redirect: route.fullPath }
    })
  }
}

onMounted(() => {
  checkLoginStatus()
  fetchBoards()
  if (isEdit.value) {
    fetchTopicDetail()
  }
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.create-topic-page {
  padding: var(--spacing-xl) 0;
  background-color: var(--bg-light);
  min-height: calc(100vh - 60px);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-lg);
  width: 100%;
}

.page-header {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  width: 100%;
  
  .page-title {
    font-size: 2rem;
    font-weight: 700;
    margin: 0;
    color: var(--text-primary);
    letter-spacing: -0.5px;
  }
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: var(--spacing-xl);
  width: 100%;
}

.form-container {
  background-color: white;
  border-radius: var(--border-radius);
  padding: var(--spacing-xl);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  width: 100%;
  
  &:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }
}

// 板块选择样式
.board-selection {
  margin-bottom: var(--spacing-md);
  width: 100%;
}

.board-option {
  display: flex;
  align-items: center;
  padding: var(--spacing-xs) 0;
  
  .board-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    border-radius: 10px;
    margin-right: var(--spacing-md);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    transition: transform 0.2s ease;
    
    &:hover {
      transform: scale(1.05);
    }
    
    .el-icon {
      font-size: 22px;
      color: white;
    }
  }
  
  .board-info {
    .board-name {
      font-size: 1rem;
      font-weight: 600;
      color: var(--text-primary);
      margin-bottom: 2px;
    }
    
    .board-desc {
      font-size: 0.85rem;
      color: var(--text-secondary);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 300px;
    }
  }
}

.title-input {
  font-size: 1.1rem;
  
  ::v-deep(.el-input__inner) {
    padding: 12px 15px;
    border-radius: 8px;
    border: 1px solid #dcdfe6;
    transition: all 0.3s;
    
    &:focus, &:hover {
      border-color: var(--color-primary);
      box-shadow: 0 0 0 2px rgba(var(--color-primary-rgb), 0.2);
    }
  }
}

// 编辑器容器
.editor-container {
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  overflow: hidden;
  transition: all 0.3s;
  width: 100%;
  
  &:hover, &:focus-within {
    border-color: var(--color-primary);
    box-shadow: 0 0 0 2px rgba(var(--color-primary-rgb), 0.1);
  }
  
  .content-editor {
    width: 100%;
    
    ::v-deep(.el-textarea__inner) {
      padding: 15px;
      font-family: 'Source Code Pro', monospace, sans-serif;
      line-height: 1.6;
      resize: vertical;
      width: 100%;
    }
  }
}

.editor-tips {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  margin-top: var(--spacing-sm);
  padding: var(--spacing-sm);
  background-color: var(--color-info-light);
  border-radius: var(--border-radius);
  color: var(--color-info);
  font-size: 0.9rem;
  width: 100%;
  
  .el-icon {
    font-size: 16px;
  }
}

// 表单操作
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
  margin-top: var(--spacing-lg);
  
  .cancel-btn {
    min-width: 100px;
  }
  
  .submit-btn {
    min-width: 140px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-weight: 500;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(var(--color-primary-rgb), 0.3);
    }
    
    .submit-icon {
      font-size: 18px;
    }
  }
}

// 发帖指南
.posting-guide {
  background-color: white;
  border-radius: var(--border-radius);
  padding: var(--spacing-lg);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 20px;
  align-self: start;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }
  
  .guide-header {
    margin-bottom: var(--spacing-md);
    
    .guide-title {
      font-size: 1.2rem;
      font-weight: 600;
      margin: 0;
      color: var(--text-primary);
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        color: var(--color-primary);
      }
    }
  }
  
  .guide-content {
    color: var(--text-secondary);
    
    .guide-item {
      display: flex;
      gap: var(--spacing-md);
      padding: var(--spacing-sm) 0;
      border-bottom: 1px dashed rgba(0, 0, 0, 0.06);
      
      &:last-child {
        border-bottom: none;
      }
      
      .guide-icon {
        color: var(--color-primary);
        font-size: 18px;
        flex-shrink: 0;
      }
      
      .guide-text {
        font-size: 0.9rem;
        line-height: 1.5;
      }
    }
  }
}

// 响应式调整
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .posting-guide {
    position: static;
    margin-top: var(--spacing-lg);
  }
}

@media (max-width: 768px) {
  .form-container {
    padding: var(--spacing-md);
  }
  
  .board-option {
    .board-info {
      .board-desc {
        max-width: 200px;
      }
    }
  }
  
  .page-title {
    font-size: 1.6rem;
  }
}

// 确保表单元素占满容器
:deep(.el-form) {
  width: 100%;
}

:deep(.el-form-item) {
  width: 100%;
}

:deep(.el-form-item__content) {
  width: 100%;
}
</style> 